﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Jbe.TestSuite.Infrastructure.Interface.Documents;
using Microsoft.Win32;

namespace Jbe.TestSuite.Infrastructure.Module.Presentation
{
    internal class FileDialogService : IFileDialogService
    {
        private OpenFileDialog openFileDialog;
        private SaveFileDialog saveFileDialog;


        private OpenFileDialog OpenFileDialog
        {
            get
            {
                if (openFileDialog == null)
                {
                    openFileDialog = new OpenFileDialog();
                }
                return openFileDialog;
            }
        }

        private SaveFileDialog SaveFileDialog
        {
            get
            {
                if (saveFileDialog == null)
                {
                    saveFileDialog = new SaveFileDialog();
                }
                return saveFileDialog;
            }
        }


        public bool ShowOpenFileDialog(IEnumerable<DocumentType> documentTypes, out string filename)
        {
            OpenFileDialog.Filter = GetFilter(documentTypes);
            if (OpenFileDialog.ShowDialog() == true)
            {
                filename = OpenFileDialog.FileName;
                return true;
            }
            else
            {
                filename = "";
                return false;
            }
        }

        public bool ShowSaveFileDialog(IEnumerable<DocumentType> documentTypes, Document document, out string filename)
        {
            SaveFileDialog.FileName = document.FileName;
            SaveFileDialog.Filter = GetFilter(documentTypes);
            if (SaveFileDialog.ShowDialog() == true)
            {
                filename = SaveFileDialog.FileName;
                return true;
            }
            else
            {
                filename = "";
                return false;
            }
        }

        private static string GetFilter(IEnumerable<DocumentType> documentTypes)
        {
            string extensions = "";
            foreach (DocumentType documentType in documentTypes)
            {
                extensions = AppendFilter(extensions, documentType);
            }
            return extensions + "|All Files (*.*)|*.*";
        }

        private static string AppendFilter(string filter, DocumentType documentType)
        {
            if (!String.IsNullOrEmpty(filter)) { filter += "|"; }
            filter += documentType.Description + "|*" + documentType.FileExtension;
            return filter;
        }
    }
}
